<?php
class Model_CommentsTree
{
    public $_moduleTitle = 'Comments Tree: ';
    /**
     * @var DbTable_CommentsTree
     */
    private $_db;
    
    /**
     * @var App_NSTree
     */
    private $_tree;
    
    /**
     * used for getting root id and adding comment
     * 
     * @var array
     */
    private $_condition;
    
    /**
     * Root id
     * 
     * @var int
     */
    private $_rootId;
    
    /**
     * ID of entry or question
     * 
     * @var int
     */
    private $_typeId;
    
    /**
     * Column name of entry or question
     * 
     * @var string
     */
    private $_typeCol;
    
    /**
     * @param array $condition
     * @return unknown_type
     */
    function __construct($condition)
    {
        $this->_condition = $condition;
        
        if (! is_array($this->_condition) || empty($this->_condition)) {
            throw new Zend_Exception('Condition should be an array and not empty');
        }
        $rootData = $this->_condition;
        if (empty($rootData['entry_id'])) {
            $rootData['entry_id'] = null;
        } else {
            if (empty($rootData['language_id'])) {
                throw new Zend_Exception('ID of language cannot be empty');
            }
        }
        if (empty($rootData['question_id'])) {
            $rootData['question_id'] = null;
        } else {
            //do not use language id for polls
            if (empty($rootData['language_id'])) {
                $rootData['language_id'] = null;
            }
        }
        if (empty($rootData['question_id']) && empty($rootData['entry_id'])) {
            throw new Zend_Exception('Empty input params. Cannot be empty entry_id or question_id');
        }
		
		//data for root item (required table colums)
        $rootData['user_id'] = '0';
        $rootData['status']  = 'active';
        $rootData['notify']  = '0';
        $rootData['is_edit'] = '0';
        $rootData['vote']    = '0';
        $rootData['ip']      = '0';
        $rootData['direction']    = 'ltr';
        $rootData['count_abuses'] = '0';
        $rootData['message'] = '';
        $rootData['dateadd'] = App_Date::dateTime();
        
		//nstree params
        $config = array(
            'db'        => App_Db_Adapter::getAdapter(App_Db_Adapter_Replication::CONSUMER_SERVER) , 
            'primary'   => 'id' , 
            'left'      => 'tree_left' , 
            'right'     => 'tree_right' , 
            'level'     => 'tree_level' , 
            'table'     => 'comments' , //comments tree table
            'condition' => $this->_condition  , 
            'rootData'  => $rootData  , 
            'type'      => Cruiser_NSTree::TYPE_SINGLE);
        $this->_tree = new App_NSTree($config);
        
		//someone db model
        $this->_db = new DbTable_CommentsTree();
        
        if (! empty($this->_condition['entry_id'])) {
            $this->_typeCol = 'entry_id';
            $this->_typeId  = $this->_condition['entry_id'];
        } elseif (! empty($this->_condition['question_id'])) {
            $this->_typeCol = 'question_id';
            $this->_typeId  = $this->_condition['question_id'];
        }
        
        if (empty($this->_typeCol) || empty($this->_typeId)) {
            throw new Zend_Exception('Unknown type of comments tree');
        }
        $this->_db = new DbTable_CommentsTree();
    }
    
    /**
     * Get main model
     * 
     * @return App_NSTree
     */
    function getTreeModel()
    {
        return $this->_tree;
    }
    
    /**
     * Get root id of comments tree by coondition
     * 
     * @return int
     */
    function getRootId()
    {
        $result = $this->_tree->getRootId();
        return $result;
    }
    
    /**
     * Get total count
     * 
     * @return int
     */
    function getCountTotal($params = array())
    {
        $languageId = $this->_condition['language_id'];
        return $this->_db->getCountTotal($this->_typeCol, $this->_typeId, 
            App_Settings::getUserIdSelf(), $languageId, $params);
    }
    
    /**
     * Get tree comments
     * 
     * @param array $params     Params to get tree
     *                   sort - Order by newest_first(right)/(left)
     *                   page - Current page
     *                 onPage - Count items on page
     *                  depth - Depth of tree
     *                          
     * @param int $userId       User id used when need to show self comments
     * @param int $id
     * @return Model_CommentsTree_Data
     */
    function getTree($params, $userId, $id)
    {
        $onPage = @ (int) $params['onPage'];
        $page   = @ $params['page'];
        $depth  = @ $params['depth'];
        
        //get branches with self comments only
        $withUserOnly = (bool) @ $params['withUserOnly'];
        
        switch (@ $params['sort']) {
            case 'newest_first':
                $sortTree = 'right';
                break;
            default:
                $sortTree = 'left';
                break;
        }
        
		$params = array(
			'convert'=> Cruiser_NSTree::CONVERT_SIMPLE_CLASS , 
			'depth'  => $depth , 
			'order'  => $sortTree , 
			//get db select adapter
			'select' => $this->_db->getSelectToGet($userId) , 
		);
		
		$dataTree = $this->_getTree($id, $params);
		$total    = $dataTree->count;
       
        $data['data']  = $dataTree;
        $data['count'] = $total;
        
        return new Model_CommentsTree_Data($data);
    }
    
    /**
     * Get data tree
     * 
     * @param int $id
     * @return array
     */
    private function _getTree($id, $params = array())
    {
        $result = $this->_tree->getTree($id, $params);
        return $result;
    }
    
    /**
     * Add child to parent node
     * 
     * @param array $data   Data to paste
     * @param $parentId     Id of parent node. If NULL then used rood node
     * @return Cruiser_NSTree_Node
     */
    function add($data, $parentId = null)
    {
        if ($parentId) {
            $data['master_id'] = $this->_db->getIdTop($parentId, $this->_condition);
            $data['parent_id'] = $parentId;
        } else {
            $data['parent_id'] =
            $data['master_id'] = null;
        }
        $node = $this->_tree->add($data, $parentId);
        return $node;
    }
}